package it.francescogabbrielli.android.solidalapp.actions;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Log;
import it.francescogabbrielli.android.solidalapp.Action;
import it.francescogabbrielli.android.solidalapp.Constants;
import it.francescogabbrielli.android.solidalapp.EndpointsUtils;
import it.francescogabbrielli.android.solidalapp.R;
import it.francescogabbrielli.android.solidalapp.SolidalApp;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.profileendpoint.Profileendpoint;
import it.francescogabbrielli.android.solidalapp.profileendpoint.model.Profile;

/**
 * Insert profile data
 */
public class EndpointsInsertProfile extends Action {

	private Profile profile;
	
	@Override
	public void execute() throws Exception {
		
		Profile profile = new Profile();
		profile.setGoogleId(prefs.getString(Constants.PROFILE_ACCOUNT, ""));
		TelephonyManager tel = (TelephonyManager) app.getSystemService(
				Context.TELEPHONY_SERVICE);
		profile.setDefaultPhone(tel.getLine1Number());
		profile.setCredits(10);
		
		Log.d(getClass().getSimpleName(), "Inserting new profile");
		Profileendpoint endpoint = EndpointsUtils.buildEndpoint(Profileendpoint.class);
		this.profile = endpoint.insertProfile(profile).execute();
		
	}
	
	@Override
	public void onPostExecute() throws Exception {
		if(profile!=null) {
			app.setData(DataKey.PROFILE, profile);
			app.registerToServices();
		} else if(app.getData(DataKey.PROFILE)==null) {
			app.alert(context.getString(R.string.error_server, "Null profile?"), true);
			Log.e(SolidalApp.TAG, "Unexpected null profile");
		}
	}

}
